package zj.it.bhne.gridengineeringsurvey.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import zj.it.bhne.gridengineeringsurvey.BaseActivity;
import zj.it.bhne.gridengineeringsurvey.MyApplication;
import zj.it.bhne.gridengineeringsurvey.R;
import zj.it.bhne.gridengineeringsurvey.adapter.ReleaseMsgAdapter;
import zj.it.bhne.gridengineeringsurvey.entity.Equip;
import zj.it.bhne.gridengineeringsurvey.entity.EquipModuleType;
import zj.it.bhne.gridengineeringsurvey.entity.ImageBean;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Equipment;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Items;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Line;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Photos;
import zj.it.bhne.gridengineeringsurvey.entity.greendao.Points;
import zj.it.bhne.gridengineeringsurvey.myutils.MyUtils;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.EquipmentDao;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.ItemsDao;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.LineDao;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.PhotosDao;
import zj.it.bhne.gridengineeringsurvey.myutils.greendao.PointsDao;

import static zj.it.bhne.gridengineeringsurvey.myutils.MyUtils.Distance;
import static zj.it.bhne.gridengineeringsurvey.myutils.MyUtils.openDatabase;

/**
 * 修改项目的活动
 */
public class EquActivity extends BaseActivity implements View.OnClickListener, ReleaseMsgAdapter.OnDeleteItemListener {

    private static final String TAG = "EquActivity";
    private ReleaseMsgAdapter adapter;
    private Context context;
    private Long cid, id;
    private Points points;
    private List<Photos> photosList = new ArrayList<>();
    private Spinner map_sp_dixing_sort;
    private Spinner map_sp_state;
    private EditText map_ed_note;
    private List<zj.it.bhne.gridengineeringsurvey.entity.bean.ModluleType> string = new ArrayList<>();
    private List<zj.it.bhne.gridengineeringsurvey.entity.bean.ModluleType> strings = new ArrayList<>();
    private List<zj.it.bhne.gridengineeringsurvey.entity.bean.ModluleType> secondeData = new ArrayList<>();
    private List<zj.it.bhne.gridengineeringsurvey.entity.bean.ModluleType> resultData = new ArrayList<>();
    private List<ModuleType> resultDatas = new ArrayList<>();


    private int lever = 0;
    private int two = 0;
    private int three = 0;
    private int four = 0;
    private Spinner map_sp_equ;
    private EditText map_ed_high;
    private LinearLayout linearLayout, layout;
    private List<Equipment> equipmentList = new ArrayList<>();
    private List<Equipment> getEquipmentList = new ArrayList<>();
    private List<ModuleType> modelTypes = new ArrayList<>();
    private List<ModuleType> moduleTypes = new ArrayList<>();
    private List<ModuleType> moduleEnd = new ArrayList<>();
    private ArrayList<Equip> equipList = new ArrayList<>();
    private List<ModuleType> threeModel = new ArrayList<>();
    private List<ModuleType> threeModule = new ArrayList<>();
    private List<ImageBean> imageBeanList = new ArrayList<>();
    private EditText map_ed_length;
    private EditText map_ed_width;
    private List<ImageBean> beanList = new ArrayList<>();
    private List<ModuleType> fourModule = new ArrayList<>();
    private List<ModuleType> endModule = new ArrayList<>();

    private String moduleCode;
    private int equId;
    private int flag = 0;
    private AlertDialog dialog;

    /**
     * 根据值, 设置spinner默认选中:
     *
     * @param spinner 传入spinner控件
     * @param value   传入与之匹配的值
     */
    public static void setSpinnerItemSelectedByValue(Spinner spinner, @NonNull String value) {
        try {
            SpinnerAdapter apsAdapter = spinner.getAdapter(); //得到SpinnerAdapter对象
            int k = apsAdapter.getCount();
            for (int i = 0; i < k; i++) {
                if (apsAdapter.getItem(i).toString() != null) {
                    if (value.equals(apsAdapter.getItem(i).toString())) {
                        spinner.setSelection(i, true);// 默认选中项
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_equ);
        context = this;
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        Intent intent = getIntent();
        cid = intent.getLongExtra("cid", 0);
        id = intent.getLongExtra("id", 0);
        initData();
        initView();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        if (cid != 0) {
            try {
                points = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Id.eq(cid)).build().list().get(0);
                photosList = MyApplication.getInstances().getPhotosDao().queryBuilder().where(PhotosDao.Properties.Points_id.eq(cid)).build().list();
                equipmentList = MyApplication.getInstances().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.Point_id.eq(cid), EquipmentDao.Properties.Qubie.eq(0)).build().list();
                getEquipmentList = MyApplication.getInstances().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.Point_id.eq(cid), EquipmentDao.Properties.Qubie.eq(2)).build().list();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                cid = MapActivity.bid;
                points = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Id.eq(cid)).build().list().get(0);
                photosList = MyApplication.getInstances().getPhotosDao().queryBuilder().where(PhotosDao.Properties.Points_id.eq(cid)).build().list();
                equipmentList = MyApplication.getInstances().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.Point_id.eq(cid), EquipmentDao.Properties.Qubie.eq(0)).build().list();
                getEquipmentList = MyApplication.getInstances().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.Point_id.eq(cid), EquipmentDao.Properties.Qubie.eq(2)).build().list();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 获取设备信息
     *
     * @param str 设备ID
     * @return 设备信息
     */
    public List<Equip> getModules(int str) {
        List<Equip> strings = new ArrayList<>();
        SQLiteDatabase db = openDatabase(context);
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from EquipType where component=" + str, null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            Equip equip = new Equip();
            equip.setId(cursor.getInt(0));
            equip.setName(cursor.getString(1));
            equip.setCode(cursor.getString(4));
            strings.add(equip);
        }
        cursor.close();
        db.close();
        return strings;
    }

    /**
     * 初始化界面
     */
    @SuppressLint("SetTextI18n")
    private void initView() {
        initRecyclerView();
        addLinearLayout();
        EditText map_ed_address = findViewById(R.id.map_ed_address);
        LinearLayout map_ll_address = findViewById(R.id.map_ll_address);
        map_ed_length = findViewById(R.id.map_ed_length);
        map_ed_width = findViewById(R.id.map_ed_width);
        RelativeLayout equ_rl_fs = findViewById(R.id.equ_rl_fs);
        LinearLayout equ_ll_dmt = findViewById(R.id.equ_ll_dmt);
        LinearLayout map_ll = findViewById(R.id.map_ll);
        LinearLayout map_ll_gl = findViewById(R.id.map_ll_gl);

        TextView equ_btn_equ = findViewById(R.id.equ_btn_equ);
        equ_btn_equ.setOnClickListener(this);
        ImageButton activity_ib_back = findViewById(R.id.activity_ib_back);
        activity_ib_back.setOnClickListener(this);
        TextView activity_tv_title = findViewById(R.id.activity_tv_title);
        activity_tv_title.setOnClickListener(this);
        TextView activity_tv_save = findViewById(R.id.activity_tv_save);
        activity_tv_save.setOnClickListener(this);
        activity_tv_title.setText(getString(R.string.title_xinxi));
        activity_tv_save.setText(getString(R.string.map_quxiao));
        TextView equ_btn_add = findViewById(R.id.equ_btn_add);
        equ_btn_add.setOnClickListener(this);
        TextView map_sp_sort = findViewById(R.id.map_sp_sort);
        TextView map_sp_type = findViewById(R.id.map_sp_type);
        TextView map_tv_dixing_sort = findViewById(R.id.map_tv_dixing_sort);
        map_sp_dixing_sort = findViewById(R.id.map_sp_dixing_sort);
        final TextView map_ed_name = findViewById(R.id.map_ed_name);
        map_sp_state = findViewById(R.id.map_sp_state);
        TextView map_tv_location = findViewById(R.id.map_tv_location);
        map_ed_note = findViewById(R.id.map_ed_note);
        RelativeLayout map_ll_dixing_sort = findViewById(R.id.map_ll_dixing_sort);

        try {
            map_ed_name.setText(points.getMark());
            map_tv_location.setText("" + points.getLat() + "、" + points.getLon());
        } catch (Exception e) {
            e.printStackTrace();
        }
        switch (points.getName()) {
            case "地形点":
                map_ll_gl.setVisibility(View.INVISIBLE);
                map_ll_address.setVisibility(View.VISIBLE);
                equ_rl_fs.setVisibility(View.GONE);
                equ_ll_dmt.setVisibility(View.GONE);
                equ_btn_equ.setVisibility(View.GONE);
                map_ll.setVisibility(View.VISIBLE);
                map_ed_address.setText(points.getAddress());
                map_ed_length.setText(points.getLength());
                map_ed_width.setText(points.getWidth());
                map_tv_dixing_sort.setVisibility(View.VISIBLE);
                map_ll_dixing_sort.setVisibility(View.VISIBLE);
                final List<Equip> dixingList = getModules(4);
                map_sp_sort.setText("地形点");
                List<String> adapter_dataq = new ArrayList<>();
                for (int i = 0; i < dixingList.size(); i++) {
                    adapter_dataq.add(dixingList.get(i).getName());
                    equipList.add(dixingList.get(i));
                }
                //适配器
                ArrayAdapter<String> arr_adapterq = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, adapter_dataq);
                //设置样式
                arr_adapterq.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

                break;
            case "杆塔":
                final List<Equip> gantaList = getModules(1);
                map_sp_sort.setText("杆塔");
                List<String> adapter_data1 = new ArrayList<>();
                for (int i = 0; i < gantaList.size(); i++) {
                    adapter_data1.add(gantaList.get(i).getName());
                    equipList.add(gantaList.get(i));
                }
                //适配器
                ArrayAdapter<String> arr_adapter1 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, adapter_data1);
                //设置样式
                arr_adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

                break;
            default:
                final List<Equip> shebeiList = getModules(2);
                map_sp_sort.setText("设备");
                List<String> adapter_data3 = new ArrayList<>();
                for (int i = 0; i < shebeiList.size(); i++) {
                    adapter_data3.add(shebeiList.get(i).getName());
                    equipList.add(shebeiList.get(i));
                }
                //适配器
                ArrayAdapter<String> arr_adapter3 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, adapter_data3);
                //设置样式
                arr_adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

                break;
        }

        Button map_btn_cancel = findViewById(R.id.map_btn_cancel);
        map_btn_cancel.setOnClickListener(this);
        Button map_btn_add = findViewById(R.id.map_btn_add);
        map_btn_add.setOnClickListener(this);
        map_sp_equ = findViewById(R.id.map_sp_equ);
        map_ed_high = findViewById(R.id.map_ed_high);
        List<Points> pointsList = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Items_id.eq(id)).build().list();
        List<String> adapter_data = new ArrayList<>();
        for (int i = 0; i < pointsList.size(); i++) {
            if (!pointsList.get(i).getMark().contains("DX"))
                adapter_data.add(pointsList.get(i).getMark());
        }
        //适配器
        ArrayAdapter<String> arr_adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, adapter_data);
        //设置样式
        arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        map_sp_equ.setAdapter(arr_adapter);
        if (points.getGlsb() != null)
            setSpinnerItemSelectedByValue(map_sp_equ, points.getGlsb());
        if (points.getSblx() != null)
            map_sp_type.setText(points.getSblx());
        equId = points.getEqu_id();

        map_ed_high.setText(points.getHigh());

        setSpinnerItemSelectedByValue(map_sp_state, points.getOld());
    }

    /**
     * 添加设备
     */
    @SuppressLint("SetTextI18n")
    private void addLinearLayout() {
        linearLayout = getWindow().getDecorView().findViewById(R.id.equ_ll);
        layout = getWindow().getDecorView().findViewById(R.id.equ_ll_fu);
        //添加的设备不为空时，添加新的View
        if (equipmentList.size() > 0) {
            linearLayout.removeAllViews();
            for (int i = 0; i < equipmentList.size(); i++) {

                View view = View.inflate(context, R.layout.activity_equ_equ, null);
                TextView equ_ed_lever = view.findViewById(R.id.equ_ed_lever);
                TextView equ_tv_name = view.findViewById(R.id.equ_tv_name);
                TextView equ_tv_xuan = view.findViewById(R.id.equ_tv_xuan);
                TextView equ_tv_amount = view.findViewById(R.id.equ_tv_amount);
                Button equ_btn_delete = view.findViewById(R.id.equ_btn_delete);
                if (!equipmentList.get(i).getFour_name().equals("")) {
                    equ_ed_lever.setText(equipmentList.get(i).getFour_name());
                } else if (!equipmentList.get(i).getThree_name().equals("")) {
                    equ_ed_lever.setText(equipmentList.get(i).getThree_name());
                } else {
                    equ_ed_lever.setText(equipmentList.get(i).getTwo_name());
                }
                equ_tv_name.setText(equipmentList.get(i).getName());

                equ_tv_amount.setText(equipmentList.get(i).getAmount() + "");
                linearLayout.addView(view);
                final int finalI = i;
                equ_btn_delete.setOnClickListener(v -> {

                    if (equipmentList.size() > 1) {
                        MyApplication.getInstances().getEquipmentDao().deleteByKey(equipmentList.get(finalI).getId());
                        initData();
                        addLinearLayout();
                    } else {
                        MyApplication.getInstances().getEquipmentDao().deleteByKey(equipmentList.get(finalI).getId());
                        linearLayout.removeAllViews();
                    }

                });
                equ_tv_xuan.setOnClickListener(v -> addEqu(equipmentList.get(finalI).getId()));
            }
        }


        //添加的附属设备设备不为空时，添加新的View
        if (getEquipmentList.size() > 0) {
            layout.removeAllViews();
            for (int i = 0; i < getEquipmentList.size(); i++) {
                View view = View.inflate(context, R.layout.activity_equ_equ, null);
                TextView equ_ed_lever = view.findViewById(R.id.equ_ed_lever);
                TextView equ_tv_name = view.findViewById(R.id.equ_tv_name);
                TextView equ_tv_xuan = view.findViewById(R.id.equ_tv_xuan);
                TextView equ_tv_amount = view.findViewById(R.id.equ_tv_amount);
                Button equ_btn_delete = view.findViewById(R.id.equ_btn_delete);

                try {
                    if (!getEquipmentList.get(i).getFour_name().equals("")) {
                        equ_ed_lever.setText(getEquipmentList.get(i).getFour_name());
                    } else if (!getEquipmentList.get(i).getThree_name().equals("")) {
                        equ_ed_lever.setText(getEquipmentList.get(i).getThree_name());
                    } else {
                        equ_ed_lever.setText(getEquipmentList.get(i).getTwo_name());
                    }

                    equ_tv_name.setText(getEquipmentList.get(i).getName());
                    equ_tv_amount.setText(getEquipmentList.get(i).getAmount() + "");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                layout.addView(view);
                final int finalI = i;
                equ_btn_delete.setOnClickListener(v -> {

                    if (getEquipmentList.size() > 1) {
                        MyApplication.getInstances().getEquipmentDao().deleteByKey(getEquipmentList.get(finalI).getId());
                        initData();
                        addLinearLayout();
                    } else {
                        MyApplication.getInstances().getEquipmentDao().deleteByKey(getEquipmentList.get(finalI).getId());
                        layout.removeAllViews();
                    }

                });
                equ_tv_xuan.setOnClickListener(v -> addFushu(getEquipmentList.get(finalI).getId()));
            }
        }
    }

    private void initRecyclerView() {
        if (photosList.size() > 0) {
            for (int i = 0; i < photosList.size(); i++) {
                imageBeanList.add(new ImageBean(photosList.get(i).getName(), photosList.get(i).getPath()));
            }
        }
        RecyclerView mEquRecyclerView = findViewById(R.id.equ_recyclerView);
        adapter = new ReleaseMsgAdapter(this, imageBeanList);
        mEquRecyclerView.setAdapter(adapter);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        mEquRecyclerView.setLayoutManager(gridLayoutManager);
        adapter.setOnDeleteItemListener(this);
        //多媒体不为空时，显示RecyclerView
        if (mEquRecyclerView.getRecycledViewPool() != null) {
            mEquRecyclerView.getRecycledViewPool().setMaxRecycledViews(0, 10);
        }

    }

    @Override
    public void OnDeleteItem(int position) {
        beanList.add(imageBeanList.get(position));
        imageBeanList.remove(position);
        //FileUtils.deleteFile(imageBeanList.get(position).getPath());
        adapter.notifyDataSetChanged();
    }

    /**
     * 通过id获得设备类型id
     *
     * @param str id
     * @return 设备类型id所需值
     */
    public List<Integer> getModuleTypeId(long str) {
        List<Integer> strings = new ArrayList<>();
        SQLiteDatabase db = openDatabase(EquActivity.this);
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from 'equip_moduleType' where equipID=" + str, null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            strings.add(cursor.getInt(2));
        }
        cursor.close();
        db.close();
        return strings;
    }

    /**
     * 按钮的点击事件
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_ib_back:
                finish();
                startActivity(new Intent(context, MapActivity.class));
                break;
            case R.id.activity_tv_save:
                finish();
                startActivity(new Intent(context, MapActivity.class));
                break;
            case R.id.map_btn_cancel:
                finish();
                startActivity(new Intent(context, MapActivity.class));
                break;
            case R.id.map_btn_add:
                save();
                break;
            //TODO 弹窗
            case R.id.equ_btn_equ:
                addEqu((long) -20);
                break;
            case R.id.equ_btn_add:
                addFushu((long) -20);
                break;
        }
    }

    /**
     * 添加附属设备
     */
    private void addFushu(final long num) {
        final View views = View.inflate(context, R.layout.activity_equ_dialog, null);
        final Spinner map_ed_lever = views.findViewById(R.id.map_ed_lever);
        final Spinner map_ed_head = views.findViewById(R.id.map_ed_head);
        final Spinner map_sp_three = views.findViewById(R.id.map_sp_three);
        final Spinner map_sp_four = views.findViewById(R.id.map_sp_four);
        final EditText map_ed_four = views.findViewById(R.id.map_ed_four);
        Button map_btn_quxiao = views.findViewById(R.id.map_btn_quxiao);
        Button map_btn_queding = views.findViewById(R.id.map_btn_queding);
        TextView map_tv_title = views.findViewById(R.id.map_tv_title);
        map_tv_title.setText("添加附属设备");
        final List<ModuleType> stringss = new ArrayList<>();
        List<Integer> modleIdList = getModuleTypeId(id);
        if (modleIdList.size() > 0) {
            for (int i = 0; i < modleIdList.size(); i++) {
                SQLiteDatabase db = openDatabase(EquActivity.this);
                assert db != null;
                //Log.e(TAG, "onItemSelected: " + modleIdList.get(i));
                @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from ModuleType where ModuleTypeID=" + "'" + modleIdList.get(i) + "'", null);//此处的db是表名，name是列名
                ModuleType equip = new ModuleType();
                while (cursor.moveToNext()) {
                    equip.setModuleTypeID(cursor.getString(0));
                    equip.setName(cursor.getString(1));
                    equip.setModuleTypeKey(cursor.getString(2));
                    stringss.add(equip);
                }
                cursor.close();
                db.close();
            }
            final List<String> adapter_data21 = new ArrayList<>();
            for (ModuleType moduleType : stringss) {
                adapter_data21.add(moduleType.getName());
            }
            //适配器
            ArrayAdapter<String> arr_adapter21 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, adapter_data21);
            //设置样式
            arr_adapter21.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            map_ed_lever.setAdapter(arr_adapter21);

            map_ed_lever.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    //Log.e(TAG, "onItemSelected: " + stringss.get(position).getModuleTypeKey());
                    string = getModuleAll(stringss.get(position).getModuleTypeKey());
                    lever = Integer.parseInt(stringss.get(position).getModuleTypeID());
                    final List<String> adapter_data4 = new ArrayList<>();
                    if (string.size() > 0) {
                        for (zj.it.bhne.gridengineeringsurvey.entity.bean.ModluleType moduleType : string) {
                            adapter_data4.add(moduleType.getModuleTypeName());
                        }
                    }
                    //适配器
                    if (adapter_data4.size() > 0) {
                        map_ed_head.setVisibility(View.VISIBLE);
                        ArrayAdapter<String> arr_adapter4 = new ArrayAdapter<>(EquActivity.this, android.R.layout.simple_spinner_item, adapter_data4);
                        //设置样式
                        arr_adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        map_ed_head.setAdapter(arr_adapter4);
                    } else {
                        map_ed_head.setVisibility(View.GONE);
                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

            map_ed_head.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    modelTypes.clear();
                    modelTypes = getModuleWf(string.get(position).getModuleTypeKey());
                    two = Integer.parseInt(string.get(position).getModuleTypeID());
                    final List<String> adapter_data4 = new ArrayList<>();

                    if (modelTypes.size() > 0) {
                        for (ModuleType moduleType : modelTypes) {
                            adapter_data4.add(moduleType.getName());
                        }
                    }

                    ArrayAdapter<String> arr_adapter4 = new ArrayAdapter<>(EquActivity.this, android.R.layout.simple_spinner_item, adapter_data4);
                    if (adapter_data4.size() > 0) {
                        //设置样式
                        map_sp_three.setVisibility(View.VISIBLE);
                        arr_adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        map_sp_three.setAdapter(arr_adapter4);
                    } else {
                        map_sp_three.setVisibility(View.GONE);
                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

            map_sp_three.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    threeModel = getModuleWf(modelTypes.get(position).getModuleTypeKey());
                    three = Integer.parseInt(modelTypes.get(position).getModuleTypeID());
                    final List<String> adapter_data4 = new ArrayList<>();


                    if (threeModel.size() > 0) {
                        for (ModuleType moduleType : threeModel) {
                            adapter_data4.add(moduleType.getName());
                        }
                    }

                    if (adapter_data4.size() > 0) {
                        map_sp_four.setVisibility(View.VISIBLE);
                        ArrayAdapter<String> arr_adapter4 = new ArrayAdapter<>(EquActivity.this, android.R.layout.simple_spinner_item, adapter_data4);
                        //设置样式
                        arr_adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        map_sp_four.setAdapter(arr_adapter4);
                    } else {
                        map_sp_four.setVisibility(View.GONE);
                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

            map_sp_four.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    four = Integer.parseInt(threeModel.get(position).getModuleTypeID());
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

            AlertDialog dialog = new AlertDialog.Builder(context).create();
            dialog.setView(views);
            dialog.show();
            map_btn_quxiao.setOnClickListener(view -> {
                KeyboardUtils.hideSoftInput(views);
                dialog.dismiss();
            });
            map_btn_queding.setOnClickListener(view -> {
                KeyboardUtils.hideSoftInput(views);
                dialog.dismiss();
                if (num > 0) {
                    Equipment equipment = new Equipment();
                    equipment.setName(map_ed_lever.getSelectedItem().toString().trim());
                    equipment.setLever_id(lever);
                    equipment.setPoint_id(cid);
                    equipment.setHead_id(two);
                    equipment.setTwo_name(map_ed_head.getSelectedItem().toString().trim());

                    if (map_sp_three.getVisibility() == View.VISIBLE) {
                        equipment.setThree_id(three);
                        equipment.setThree_name(map_sp_three.getSelectedItem().toString().trim());
                    }
                    if (map_sp_four.getVisibility() == View.VISIBLE) {
                        equipment.setFour_name(map_sp_four.getSelectedItem().toString().trim());
                        equipment.setFour_id(four);
                    }
                    equipment.setId(num);
                    equipment.setQubie(2);
                    if (map_ed_four.getText().toString().trim().equals("")) {
                        equipment.setAmount(1);
                    } else {
                        equipment.setAmount(Integer.parseInt(map_ed_four.getText().toString().trim()));
                    }
                    MyApplication.getInstances().getEquipmentDao().update(equipment);
                } else {
                    Equipment equipment = new Equipment();
                    equipment.setPoint_id(cid);
                    equipment.setId(null);
                    equipment.setQubie(2);
                    equipment.setName(map_ed_lever.getSelectedItem().toString().trim());
                    equipment.setLever_id(lever);
                    equipment.setHead_id(two);

                    if (map_sp_three.getVisibility() == View.VISIBLE) {
                        equipment.setThree_id(three);
                        equipment.setThree_name(map_sp_three.getSelectedItem().toString().trim());
                    }
                    if (map_sp_four.getVisibility() == View.VISIBLE) {
                        equipment.setFour_name(map_sp_four.getSelectedItem().toString().trim());
                        equipment.setFour_id(four);
                    }
                    try {
                        equipment.setTwo_name(map_ed_head.getSelectedItem().toString().trim());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if (map_ed_four.getText().toString().trim().equals("")) {
                        equipment.setAmount(1);
                    } else {
                        equipment.setAmount(Integer.parseInt(map_ed_four.getText().toString().trim()));
                    }
                    MyApplication.getInstances().getEquipmentDao().insert(equipment);
                }
                initData();
                addLinearLayout();
            });
        } else {
            ToastUtils.showShort("当前没有可添加的附属设备");
        }
    }

    /**
     * 添加设备
     */
    //TODO 开始
    private void addEqu(final Long num) {
        final View views = View.inflate(context, R.layout.activity_equ_dialogs, null);
        final Spinner map_ed_lever = views.findViewById(R.id.map_ed_lever);
        final Spinner map_ed_head = views.findViewById(R.id.map_ed_head);
        final Spinner map_sp_three = views.findViewById(R.id.map_sp_three);
        final Spinner map_sp_four = views.findViewById(R.id.map_sp_four);
        final EditText map_ed_four = views.findViewById(R.id.map_ed_four);
        final Spinner map_sp_five = views.findViewById(R.id.map_sp_five);
        TextView map_tv_title = views.findViewById(R.id.map_tv_title);
        Button map_btn_quxiao = views.findViewById(R.id.map_btn_quxiao);
        Button map_btn_queding = views.findViewById(R.id.map_btn_queding);
        //TODO 拿着ID去查询equip_moduleType里面的 对呀设备名称
        List<EquipModuleType> equipModuleTypeList = getEquipId(equId);
        List<zj.it.bhne.gridengineeringsurvey.entity.bean.ModluleType> moduleTypeList = new ArrayList<>();
        for (int index = 0; index < equipModuleTypeList.size(); index++) {
            Log.e("equTpye", equipModuleTypeList.get(index).getModuleTypeID() + "");
            moduleTypeList.addAll(getModluleType(equipModuleTypeList.get(index).getModuleTypeID()));
        }
        Log.e("erro=", moduleTypeList.toString());
        final List<String> adapter_data21 = new ArrayList<>();
        for (int s = 0; s < moduleTypeList.size(); s++) {
            adapter_data21.add(moduleTypeList.get(s).getModuleTypeName());
        }
        map_tv_title.setText("添加设备");
        //适配器
        ArrayAdapter<String> arr_adapter21 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, adapter_data21);
        //TODO 第一步添加设备名称
        arr_adapter21.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        map_ed_lever.setAdapter(arr_adapter21);
        //TODO 第二部添加设备名称
        map_ed_lever.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                secondeData.clear();
                //TODO 这里进入ModuleType数据表的一级查询。如果
                secondeData = getModule(moduleTypeList.get(position).getModuleTypeKey());
                //TODO 如果没有下一级别这里进行获取最后一级别所有的结果
                if (secondeData.size() <= 0) {
                    map_ed_head.setVisibility(View.GONE);
                    secondeData.addAll(moduleTypeList);
                    moduleTypes = getAllModuleName(secondeData.get(position).getModuleTypeKey());
                    two = Integer.parseInt(secondeData.get(position).getModuleTypeID());
                    final List<String> adapter_data4 = new ArrayList<>();
                    for (ModuleType moduleType : moduleTypes) {
                        adapter_data4.add(moduleType.getName());
                    }
                    //TODO 这里是最后的结果。因为就有第一级
                    ArrayAdapter<String> arr_adapter4 = new ArrayAdapter<>(EquActivity.this, android.R.layout.simple_spinner_item, adapter_data4);
                    if (adapter_data4.size() > 0) {
                        //设置样式
                        map_sp_three.setVisibility(View.VISIBLE);
                        arr_adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        map_sp_three.setAdapter(arr_adapter4);
                    } else {
                        map_sp_three.setVisibility(View.GONE);
                    }
                } else {//TODO 如果有下一级别这里进行显示第二集体为第一次查询的结果。并且这里有第三级的负值
                    final List<String> adapter_data4 = new ArrayList<>();
                    for (zj.it.bhne.gridengineeringsurvey.entity.bean.ModluleType moduleTypes : secondeData) {
                        adapter_data4.add(moduleTypes.getModuleTypeName());
                    }
                    //适配器
                    ArrayAdapter<String> arr_adapter4 = new ArrayAdapter<>(EquActivity.this, android.R.layout.simple_spinner_item, adapter_data4);
                    //设置样式
                    arr_adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    map_ed_head.setAdapter(arr_adapter4);
                    //TODO 这里获取所有的第三级去Modle表里面获取值

                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        //TODO 设置样式第二个
        map_ed_head.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //TODO 获取默认的第一个对应的结果
                resultDatas.clear();
                resultData.clear();
                resultData = getModuleAll(secondeData.get(position).getModuleTypeKey());
                for (int index = 0; index < resultData.size(); index++) {
                    resultDatas.addAll(getAllModuleName(resultData.get(index).getModuleTypeKey()));
                }

                final List<String> adapter_data4 = new ArrayList<>();
                for (ModuleType moduleType : resultDatas) {
                    adapter_data4.add(moduleType.getName());
                }
                //适配器
                ArrayAdapter<String> arr_adapter4 = new ArrayAdapter<>(EquActivity.this, android.R.layout.simple_spinner_item, adapter_data4);
                if (adapter_data4.size() > 0) {
                    //设置样式
                    map_sp_three.setVisibility(View.VISIBLE);
                    arr_adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    map_sp_three.setAdapter(arr_adapter4);
                } else {
                    map_sp_three.setVisibility(View.GONE);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        map_sp_three.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                  /*  moduleTypesData.clear();
                    endModule.clear();
                    threeModule = getModuleAll(moduleTypes.get(position).getModuleTypeKey());// getModule(moduleTypes.get(position).getModuleTypeKey());
                    if (threeModel.size() > 0) {
                        for (int i = 0; i < threeModel.size(); i++) {
                            threeModule.addAll(getModuleEnd(threeModel.get(i).getModuleTypeKey()));
                        }
                    }
                    three = Integer.parseInt(moduleTypes.get(position).getModuleTypeID());
                    final List<String> adapter_data4 = new ArrayList<>();

                    for (int i = 0; i < fourModule.size(); i++) {
                        endModule.addAll(getAllModuleName(fourModule.get(i).getModuleTypeKey()));
                    }
                    for (ModuleType moduleType : endModule) {
                        adapter_data4.add(moduleType.getName());
                    }
                    //适配器
                    ArrayAdapter<String> arr_adapter4 = new ArrayAdapter<>(EquActivity.this, android.R.layout.simple_spinner_item, adapter_data4);
                    if (adapter_data4.size() > 0) {
                        //设置样式
                        map_sp_four.setVisibility(View.VISIBLE);
                        arr_adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        map_sp_four.setAdapter(arr_adapter4);
                    } else {
                        map_sp_four.setVisibility(View.GONE);
                    }*/
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
           /* //TODO 第四个需要的结果
            map_sp_four.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    moduleTypesData.clear();
                    endModule.clear();
                    fourModule = getModuleAll(threeModule.get(position).getModuleTypeKey());
                    for (int i = 0; i < fourModule.size(); i++) {
                        endModule.addAll(getAllModuleName(fourModule.get(i).getModuleTypeKey()));
                    }
                    //TODO
                    Log.e("sjflsjflsl", fourModule.toString());
                    four = Integer.parseInt(threeModule.get(position).getModuleTypeID());
                    final List<String> adapter_data4 = new ArrayList<>();
                    for (ModuleType moduleType : endModule) {
                        adapter_data4.add(moduleType.getName());
                    }
                    //适配器
                    ArrayAdapter<String> arr_adapter4 = new ArrayAdapter<>(EquActivity.this, android.R.layout.simple_spinner_item, adapter_data4);

                    if (adapter_data4.size() > 0) {
                        //设置样式
                        map_sp_five.setVisibility(View.VISIBLE);
                        arr_adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        map_sp_five.setAdapter(arr_adapter4);
                    } else {
                        map_sp_five.setVisibility(View.GONE);
                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

            map_sp_five.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    four = Integer.parseInt(fourModule.get(position).getModuleTypeID());
                    moduleCode = fourModule.get(position).getModuleCode();
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });
*/

        dialog = new AlertDialog.Builder(context).create();
        dialog.setView(views);
        dialog.show();

        map_btn_quxiao.setOnClickListener(view -> {
            KeyboardUtils.hideSoftInput(views);
            dialog.dismiss();
        });
        map_btn_queding.setOnClickListener(view -> {
            KeyboardUtils.hideSoftInput(views);
            dialog.dismiss();
            if (num > 0) {
                Equipment equipment = new Equipment();
                equipment.setName(map_ed_lever.getSelectedItem().toString().trim());
                equipment.setLever_id(lever);
                equipment.setPoint_id(cid);
                equipment.setHead_id(two);
                equipment.setThree_id(three);
                equipment.setFour_id(four);
                equipment.setTwo_name(map_ed_head.getSelectedItem().toString().trim());
                equipment.setThree_name(map_sp_three.getSelectedItem().toString().trim());
                equipment.setModule_code(moduleCode);
                if (map_sp_five.getSelectedItem() == null) {
                    equipment.setFour_name(map_sp_four.getSelectedItem().toString().trim());
                } else {
                    equipment.setFour_name(map_sp_five.getSelectedItem().toString().trim());
                }
                equipment.setId(num);
                equipment.setQubie(0);
                if (map_ed_four.getText().toString().trim().equals("")) {
                    equipment.setAmount(1);
                } else {
                    equipment.setAmount(Integer.parseInt(map_ed_four.getText().toString().trim()));
                }
                MyApplication.getInstances().getEquipmentDao().update(equipment);
            } else {
                Equipment equipment = new Equipment();
                equipment.setPoint_id(cid);
                equipment.setId(null);
                equipment.setQubie(0);
                equipment.setName(map_ed_lever.getSelectedItem().toString().trim());
                equipment.setLever_id(lever);
                equipment.setHead_id(two);
                equipment.setThree_id(three);
                equipment.setFour_id(four);
                equipment.setModule_code(moduleCode);
                equipment.setTwo_name(map_ed_head.getSelectedItem().toString().trim());
                equipment.setThree_name(map_sp_three.getSelectedItem().toString().trim());
                try {
                    if (map_sp_five.getSelectedItem() == null) {
                        equipment.setFour_name(map_sp_four.getSelectedItem().toString().trim());
                    } else {
                        equipment.setFour_name(map_sp_five.getSelectedItem().toString().trim());
                    }
                } finally {
                    equipment.setFour_name(map_sp_four.getSelectedItem().toString().trim());
                }
                equipment.setLever_id(lever);
                if (map_ed_four.getText().toString().trim().equals("")) {
                    equipment.setAmount(1);
                } else {
                    equipment.setAmount(Integer.parseInt(map_ed_four.getText().toString().trim()));
                }
                MyApplication.getInstances().getEquipmentDao().insert(equipment);
            }
            initData();
            addLinearLayout();
        });
    }

    private List<ModuleType> getModuleEnd(String moduleTypeKey) {
        List<ModuleType> stringsModule = new ArrayList<>();
        SQLiteDatabase db = openDatabase(context);
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from Module where ModuleTypeKey=" + "'" + moduleTypeKey + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            ModuleType equip = new ModuleType();
            equip.setModuleTypeID(cursor.getString(0));
            equip.setName(cursor.getString(1));
            equip.setModuleTypeKey(cursor.getString(2));
            equip.setModuleCode(cursor.getString(3));
            stringsModule.add(equip);
        }
        Log.e("enene", stringsModule.toString());
        cursor.close();
        db.close();
        return stringsModule;
    }

    /**
     * 获取设备名称方法
     *
     * @moduleTypeID 设备类型Id
     */
    private List<zj.it.bhne.gridengineeringsurvey.entity.bean.ModluleType> getModluleType(int moduleTypeID) {
        List<zj.it.bhne.gridengineeringsurvey.entity.bean.ModluleType> modlutypess = new ArrayList<>();
        SQLiteDatabase db = openDatabase(this);
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from ModuleType where ModuleTypeID=" + "'" + moduleTypeID + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            zj.it.bhne.gridengineeringsurvey.entity.bean.ModluleType equip = new zj.it.bhne.gridengineeringsurvey.entity.bean.ModluleType();
            equip.setModuleTypeID(cursor.getString(0));
            equip.setModuleTypeName(cursor.getString(1));
            equip.setModuleTypeKey(cursor.getString(2));
            equip.setParentKey(cursor.getString(3));
            equip.setState(cursor.getString(4));
            equip.setLayerKey(cursor.getString(5));
            Log.e("modletype=", equip.toString());
            modlutypess.add(equip);
        }
        cursor.close();
        db.close();
        return modlutypess;

    }

    /**
     * 获取最后一个设备
     *
     * @param moduleTypeKey 设备的key
     * @return 设备集合
     */
    private List<ModuleType> getModuleLast(String moduleTypeKey) {
        List<ModuleType> strings = new ArrayList<>();
        SQLiteDatabase db = openDatabase(this);
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from Module where ModuleTypeKey=" + "'" + moduleTypeKey + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            ModuleType equip = new ModuleType();
            equip.setModuleTypeID(cursor.getString(0));
            equip.setName(cursor.getString(1));
            equip.setModuleTypeKey(cursor.getString(2));
            equip.setModuleCode(cursor.getString(3));
            strings.add(equip);
        }
        cursor.close();
        db.close();
        return strings;
    }

    /**
     * 通过点点id查询equip_modleType里面的
     *
     * @param id
     * @return 子类集合
     */
    private List<EquipModuleType> getEquipId(Integer id) {
        List<EquipModuleType> equipModuleTypeList = new ArrayList<>();
        SQLiteDatabase db = openDatabase(context);
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from equip_moduleType where equipID=" + "'" + id + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            EquipModuleType equipModuleType = new EquipModuleType();
            equipModuleType.setId(cursor.getInt(0));
            equipModuleType.setEquipID(cursor.getInt(1));
            equipModuleType.setModuleTypeID(cursor.getInt(2));
            Log.e("equpid", equipModuleType.toString());
            equipModuleTypeList.add(equipModuleType);
        }
        cursor.close();
        db.close();
        return equipModuleTypeList;
    }

    /**
     * 通过设备的父类获取子类集合
     *
     * @param parent 父类唯一标识
     * @return 子类集合
     */
    private List<ModuleType> getModuleWf(String parent) {
        List<ModuleType> strings = new ArrayList<>();
        SQLiteDatabase db = openDatabase(context);
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from ModuleType where ParentKey=" + "'" + parent + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            ModuleType equip = new ModuleType();
            equip.setModuleTypeID(cursor.getString(0));
            equip.setName(cursor.getString(1));
            equip.setModuleTypeKey(cursor.getString(2));
            equip.setParentKey(cursor.getString(3));
            strings.add(equip);
        }
        cursor.close();
        db.close();
        return strings;
    }

    /**
     * 通过设备的父类获取子类集合
     *
     * @param parent 父类唯一标识
     * @return 子类集合
     */
    private List<zj.it.bhne.gridengineeringsurvey.entity.bean.ModluleType> getModule(String parent) {
        List<zj.it.bhne.gridengineeringsurvey.entity.bean.ModluleType> strings = new ArrayList<>();
        SQLiteDatabase db = openDatabase(context);
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from ModuleType where ParentKey=" + "'" + parent + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            zj.it.bhne.gridengineeringsurvey.entity.bean.ModluleType equip = new zj.it.bhne.gridengineeringsurvey.entity.bean.ModluleType();
            equip.setModuleTypeID(cursor.getString(0));
            equip.setModuleTypeName(cursor.getString(1));
            equip.setModuleTypeKey(cursor.getString(2));
            equip.setParentKey(cursor.getString(3));
            equip.setState(cursor.getString(4));
            equip.setLayerKey(cursor.getString(5));
            strings.add(equip);
        }
        cursor.close();
        db.close();
        return strings;
    }

    private List<ModuleType> getAllModuleName(String moduleTypeKey) {
        List<ModuleType> stringsModule = new ArrayList<>();
        SQLiteDatabase db = openDatabase(context);
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from Module where ModuleTypeKey=" + "'" + moduleTypeKey + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            ModuleType equip = new ModuleType();
            equip.setModuleTypeID(cursor.getString(0));
            equip.setName(cursor.getString(1));
            equip.setModuleTypeKey(cursor.getString(2));
            equip.setModuleCode(cursor.getString(3));
            stringsModule.add(equip);
        }
        cursor.close();
        db.close();
        return stringsModule;
    }

    /**
     * 通过设备的父类获取子类集合
     *
     * @param parent 父类唯一标识
     * @return 子类集合
     */
    List<zj.it.bhne.gridengineeringsurvey.entity.bean.ModluleType> moduleTypesData = new ArrayList<>();

    private List<zj.it.bhne.gridengineeringsurvey.entity.bean.ModluleType> getModuleAll(String parent) {
        List<zj.it.bhne.gridengineeringsurvey.entity.bean.ModluleType> stringsModule = new ArrayList<>();
        SQLiteDatabase db = openDatabase(context);
        assert db != null;
        @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from ModuleType where ParentKey=" + "'" + parent + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            zj.it.bhne.gridengineeringsurvey.entity.bean.ModluleType equip = new zj.it.bhne.gridengineeringsurvey.entity.bean.ModluleType();
            equip.setModuleTypeID(cursor.getString(0));
            equip.setModuleTypeName(cursor.getString(1));
            equip.setModuleTypeKey(cursor.getString(2));
            equip.setParentKey(cursor.getString(3));
            stringsModule.add(equip);
        }
        cursor.close();
        db.close();
        moduleTypesData.addAll(stringsModule);

        if (stringsModule.size() > 0) {
            for (int i = 0; i < stringsModule.size(); i++) {
                getModuleAll(stringsModule.get(i).getModuleTypeKey());
            }
        } else {
            return moduleTypesData;
        }
        return moduleTypesData;
    }

    /**
     * 保存方法
     */
    //TODO 修改方法
    private void save() {
        points.setOld(map_sp_state.getSelectedItem().toString().trim());
        if ("".equals(map_ed_high.getText().toString().trim())) {
            points.setHigh(map_ed_high.getText().toString().trim() + "");
        } else {
            points.setHigh(map_ed_high.getText().toString().trim());
        }
        points.setNote(map_ed_note.getText().toString().trim());
        if (points.getName().equals("地形点")) {
            points.setCategory(map_sp_dixing_sort.getSelectedItem().toString().trim());
            points.setGlsb("");
            points.setWidth(map_ed_length.getText().toString());
            points.setLength(map_ed_width.getText().toString());
        } else {
            points.setGlsb(map_sp_equ.getSelectedItem().toString().trim());

            Points pointsList = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Mark.eq(map_sp_equ.getSelectedItem().toString().trim())).build().list().get(0);
            List<Line> lines = MyApplication.getInstances().getLineDao().queryBuilder().where(LineDao.Properties.Start_id.eq(points.getUid())).build().list();
            if (lines.size() > 0) {
                Line line = lines.get(0);
                line.setLatB(pointsList.getLat());
                line.setLonB(pointsList.getLon());
                line.setStart_id(points.getUid());
                line.setEnd_id(pointsList.getUid());
                if (pointsList.getName().equals("杆塔") && points.getName().equals("杆塔")) {
                    line.setType("架空线路");
                    line.setType_Id("11");
                } else {
                    line.setType("电缆");
                    line.setType_Id("42");
                }

                assert line != null;
                List<Points> pointsLists = MyApplication.getInstances().getPointsDao().queryBuilder().where(PointsDao.Properties.Items_id.eq(id)).build().list();
                if (pointsLists.size() > 1 && pointsList.getGlsb() != null && !pointsList.getGlsb().equals("")) {
                    if (pointsList.getId() != 1) {
                        BigDecimal bg = new BigDecimal(Distance(Double.valueOf(line.getLatA()), Double.valueOf(line.getLonA()), Double.valueOf(pointsList.getLat()), Double.valueOf(pointsList.getLon()))).setScale(2, RoundingMode.UP);
                        double lengths = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        line.setLength(lengths + "");
                        MyApplication.getInstances().getLineDao().update(line);
                    }
                }
            }
        }
        points.setId(cid);
        MyApplication.getInstances().getPointsDao().update(points);

        //删除图片操作
        if (beanList.size() > 0) {
            for (int i = 0; i < beanList.size(); i++) {
                for (int j = 0; j < photosList.size(); j++) {
                    if (photosList.get(j).getPath().equals(beanList.get(i).getPath())) {
                        MyApplication.getInstances().getPhotosDao().delete(photosList.get(j));
                        FileUtils.deleteFile(beanList.get(i).getPath());
                    }
                }
            }
        }
        if (imageBeanList.size() > 0) {
            savePhoto();
        }

        MyUtils.getToast(context, "保存成功");
        startActivity(new Intent(context, MapActivity.class));
        finish();
    }

    /**
     * 保存图片
     */
    private void savePhoto() {
        for (int i = 0; i < imageBeanList.size(); i++) {
            if (!imageBeanList.get(i).getPath().contains("/storage/emulated/0/bhne/")) {
                //Bitmap bitmap = BitmapFactory.decodeFile(imageBeanList.get(i).getPath());
                String mImageName = Calendar.getInstance().getTimeInMillis() + ".jpg";
                //创建图片文件
                File mImageFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                        + "/bhne/" + getPath() + "/", mImageName);
                mImageFile.getParentFile().mkdirs();
                FileUtils.copyFile(imageBeanList.get(i).getPath(), mImageFile.getPath());
                //savePhotoToSD(bitmap, mImageFile);
                Photos photos = new Photos();
                photos.setId(null);
                photos.setName(mImageName);
                photos.setPath(mImageFile.getPath());
                photos.setPoints_id(cid);
                MyApplication.getInstances().getPhotosDao().insert(photos);
            }
        }
    }

    /**
     * 得到当前Items名称
     */
    private String getPath() {
        Items items;
        if (id != 0) {
            List<Items> itemsList = MyApplication.getInstances().getItemsDao().queryBuilder().where(ItemsDao.Properties.Id.eq(id)).build().list();
            items = itemsList.get(0);
        } else {
            id = MapActivity.zid;
            List<Items> itemsList = MyApplication.getInstances().getItemsDao().queryBuilder().where(ItemsDao.Properties.Id.eq(id)).build().list();
            items = itemsList.get(0);
        }

        return items.getName();
    }


    /**
     * 处理返回结果。
     *
     * @param requestCode 请求码
     * @param resultCode  结果码 成功 -1 失败 0
     * @param data        返回的数据
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST: {
                    List<LocalMedia> paths = PictureSelector.obtainMultipleResult(data);
                    for (int i = 0; i < paths.size(); i++) {
                        imageBeanList.add(new ImageBean(paths.get(i).getCutPath(), paths.get(i).getPath()));
                    }
                    adapter.notifyDataSetChanged();
                    break;
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        finish();
    }

}